package com.twm.tamauth.service

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import com.twm.tamauth.R
import java.io.File
import java.io.FileOutputStream

class MyNotificationService : Service() {

    companion object {
        const val SCREEN_CAPTURE_CHANNEL_ID = "screen_capture_channel_id"
        const val SCREEN_CAPTURE_CHANNEL_NAME = "Screen Capture Channel"
    }
    private var callback: FloatDisplayCallback? = null
    // 设置回调的方法
    fun setFloatDisplayCallback(callback: FloatDisplayCallback) {
        this.callback = callback
    }

    private lateinit var mediaProjectionManager: MediaProjectionManager
    private var mediaProjection: MediaProjection? = null
    private var virtualDisplay: VirtualDisplay? = null
    private var imageReader: ImageReader? = null
    private lateinit var globalTextView: TextView
    private lateinit var screenshotButton: Button

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        // 获取 MediaProjectionManager 实例
        mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Log.i("MyNotificationService","创建通知渠道")

            // 创建通知渠道
            createNotificationChannels()

            // 创建通知实例
            val notification: Notification = Notification.Builder(this, SCREEN_CAPTURE_CHANNEL_ID)
                .setContentTitle("Service is running")
                .setContentText("This is the notification content")
                .setSmallIcon(R.mipmap.ic_launcher) // 设置适当的图标
                .build()

            // 启动前台服务并显示通知
            startForeground(1, notification)
        }

        intent?.let {
            // 获取录屏结果码和数据
            val resultCode = it.getIntExtra("resultCode", Activity.RESULT_CANCELED)
            Log.i("MyNotificationService","resultCode = $resultCode")

            val data = it.getParcelableExtra<Intent>("data")
            Log.i("MyNotificationService","data = $data")

            if (data != null && resultCode == Activity.RESULT_OK) {
                Log.i("MyNotificationService"," 获取 MediaProjection 实例")
                // 获取 MediaProjection 实例
                mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data)
                // 注册回调
                mediaProjection?.registerCallback(MediaProjectionCallback(), null)
                // 初始化录屏设置
                initializeScreenCapture()
                // 创建浮窗
                createFloatingWindow()
            }
        }

        return START_STICKY
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannels() {
        val notificationManager = getSystemService(NotificationManager::class.java)

        // 创建屏幕捕获通知渠道
        val screenCaptureChannel = NotificationChannel(
            SCREEN_CAPTURE_CHANNEL_ID,
            SCREEN_CAPTURE_CHANNEL_NAME,
            NotificationManager.IMPORTANCE_LOW
        )
        notificationManager.createNotificationChannel(screenCaptureChannel)
    }

    /**
     * 录屏设置
     */
    @SuppressLint("WrongConstant")
    private fun initializeScreenCapture() {
        Log.i("MyNotificationService", "录屏设置")

        // 获取屏幕指标
        val metrics = resources.displayMetrics
        // 创建 ImageReader 实例
        imageReader = ImageReader.newInstance(metrics.widthPixels, metrics.heightPixels, PixelFormat.RGBA_8888, 2)
        // 创建虚拟显示
        virtualDisplay = mediaProjection?.createVirtualDisplay(
            "ScreenCapture",
            metrics.widthPixels,
            metrics.heightPixels,
            metrics.densityDpi,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader?.surface, null, null
        )
    }

    /**
     * 浮窗
     */
    @SuppressLint("RtlHardcoded")
    private fun createFloatingWindow() {
        EasyFloat.with(this)
            .setShowPattern(ShowPattern.ALL_TIME)
            .setGravity(Gravity.RIGHT, -20, 0)
            .hasEditText(true)
            .setTag("EasyFloat-Tag")
            .setLayout(R.layout.view_but) {
                screenshotButton = it.findViewById(R.id.myButton)
                screenshotButton.setOnClickListener {
                    Log.e("MyOpenSDK", "----点击截屏----")
                    takeScreenshot()
                }
                // 下方的文字
                globalTextView = it.findViewById(R.id.describeLabel)
            }.registerCallback {
                show {
                    Log.i("MyNotificationService", "浮窗显示")
                    // 调用回调通知浮窗显示成功
                    callback?.onFloatDisplayed()
                }

                dismiss {
                    Log.i("MyNotificationService", "浮窗隐藏")
                }
            }
            .show()
    }

    /**
     * 截屏
     */
    private fun takeScreenshot() {
        val image = imageReader?.acquireLatestImage() ?: return
        val planes = image.planes
        val buffer = planes[0].buffer
        val pixelStride = planes[0].pixelStride
        val rowStride = planes[0].rowStride
        val rowPadding = rowStride - pixelStride * imageReader!!.width

        val bitmap = Bitmap.createBitmap(
            imageReader!!.width + rowPadding / pixelStride,
            imageReader!!.height,
            Bitmap.Config.ARGB_8888
        )
        bitmap.copyPixelsFromBuffer(buffer)

        saveBitmap(bitmap)
        image.close()
    }

    private fun saveBitmap(bitmap: Bitmap) {
        val file = File(getExternalFilesDir(null), "screenshot.png")
        FileOutputStream(file).use {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaProjection?.stop()
        virtualDisplay?.release()
        imageReader?.close()
    }

    private inner class MediaProjectionCallback : MediaProjection.Callback() {
        override fun onStop() {
            super.onStop()
            virtualDisplay?.release()
            imageReader?.close()
            mediaProjection = null
        }
    }
}


interface FloatDisplayCallback {
    fun onFloatDisplayed()
}
